/*
 * @Author: 别拿暗恋当饭吃. 13466071+lililkli@user.noreply.gitee.com
 * @Date: 2024-07-08 08:49:28
 * @LastEditors: 别拿暗恋当饭吃. 13466071+lililkli@user.noreply.gitee.com
 * @LastEditTime: 2024-07-11 14:57:43
 * @FilePath: \新建文件夹\doctor\src\pages\Consultationinformation\ConversatTionalchat\index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
/*
 * @Author: 别拿暗恋当饭吃. 13466071+lililkli@user.noreply.gitee.com
 * @Date: 2024-07-08 08:44:12
 * @LastEditors: 别拿暗恋当饭吃. 13466071+lililkli@user.noreply.gitee.com
 * @LastEditTime: 2024-07-09 14:38:19
 * @FilePath: \doctor\src\pages\Consultationinformation\Listofinformation\index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import React, { useCallback, useEffect, useState } from 'react';
import { NavBar } from 'antd-mobile';
import { useDispatch, useSelector } from 'react-redux'
import { doDoctorchat } from 'store/Consultationinformation/Doctorchat'
import { useNavigate } from 'react-router-dom';
import _ from 'lodash'
import './style.scss'
interface Message {
    sender: string;
    content: string;
    type: 'sent' | 'received'; // 新增消息类型字段，用于区分发送和接收的消息
}

const Index = () => {
    //navigator
    const navigator = useNavigate();
    // dispatch
    const dispatch = useDispatch<any>()
    // 路由跳转
    const navigate = useNavigate()
    //导航点击返回
    const back = () => {
        navigate(-1)
    }

    const [ws, setWs] = useState<WebSocket | null>(null);
    const [inputMessage, setInputMessage] = useState('');
    const [messages, setMessages] = useState<Message[]>([]);
    const [username, setUsername] = useState('');


    useEffect(() => {
        const username: any = localStorage.getItem("sessionId");

        // const username = prompt('请输入您的用户名:') || '匿名用户';
        setUsername(username);

        const socket = new WebSocket('ws://localhost:8080');

        socket.onopen = () => {
            setWs(socket);
        };

        socket.onmessage = (event) => {
            try {
                const message = JSON.parse(event.data);
                message.type = 'received'; // 标记为接收到的消息
                setMessages((prevMessages) => [...prevMessages, message]);
            } catch (error) {
                // console.error('Error parsing JSON:', error);
            }
        };

        socket.onerror = (error) => {
            // console.error('WebSocket 发生错误:', error);
        };

        socket.onclose = () => {
            // console.log('WebSocket 连接关闭');
        };

        return () => {
            if (socket.readyState === WebSocket.OPEN) {
                socket.close();
            }
        };
    }, []);

    const handleMessageChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        setInputMessage(event.target.value);
    };

    const sendMessage = _.throttle(() => {
        alert('ok')
        const data = {
            inquiryId: 1,
            content: inputMessage,
            type: 1,
            userId: 1,
        }
        dispatch(doDoctorchat(data))
        if (ws && ws.readyState === WebSocket.OPEN && inputMessage.trim() !== '') {
            const message: Message = {
                sender: username,
                content: inputMessage.trim(),
                type: 'sent', // 标记为发送的消息
            };
            setMessages((prevMessages) => [...prevMessages, message]);
            ws.send(JSON.stringify(message));
            setInputMessage('');
        }
    }, 10000);
    const Yonhhu = () => {
        navigate('/patientinformationpage')
    }
    return (
        <div className='box-chat'>
            {/* 导航栏 */}
            <NavBar onBack={back} style={{ borderBottom: '1px solid #c0c0c0' }}>对话聊天</NavBar>
            <div className="app-container">
                <div className="chat-container">
                    <ul>
                        {messages.map((message, index) => (
                            <li
                                onClick={Yonhhu}
                                key={index}
                                className={`message ${message.type}`}
                                style={{ marginBottom: '0.625rem', fontSize: '1rem' }}
                            >
                                {message.sender}: {message.content}
                            </li>
                        ))}
                    </ul>
                </div>
                <div className="messageInput">
                    <input
                        type="text"
                        value={inputMessage}
                        onChange={handleMessageChange}
                        placeholder="输入消息..."
                    />
                    <button onClick={sendMessage}>发送</button>
                </div>
            </div>
        </div>
    )
}

export default Index